from pydht import DHT
from db import DbThread
import Queue,threading,time



class SaveThread(threading.Thread):
    def __init__(self, queue):  
        threading.Thread.__init__(self)  
        self.queue = queue
        self.dbThreads = []
        for i in range(4):
            dbThread = DbThread()
            dbThread.setDaemon(True)
            dbThread.start()
            self.dbThreads.append( dbThread )
        self.dbThreadNum = len(self.dbThreads)
        
   
    def run(self): #Overwrite run() method, put what you want the thread do here  
        print "saveThread start"
        queue = self.queue
        threadID =  0
        while True:
            if queue.qsize()> 0:
                hash_id = queue.get()
                print "thread hash:" + hash_id
                
                self.dbThreads[threadID].put(hash_id)
                threadID = threadID+1
                if threadID >= self.dbThreadNum: threadID = 0
                
            else:
                time.sleep(1) 
                
    def stop(self):  
        self.thread_stop = True
        
            
if __name__ == "__main__":
    queue = Queue.Queue()
    d = DHT(queue)
 
    saveThread = SaveThread(queue)
    saveThread .setDaemon(True)
    saveThread.start()
    d.start('router.bittorrent.com', 6881)
    saveThread.stop()
